package com.wlstock.funi.ui;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;

import com.android.volley.VolleyError;
import com.em.baselistener.OnBackListener;
import com.em.baselistener.OnMoreListener;
import com.em.baselistener.OnTitleClickListener;
import com.em.widget.view.SelectPopUpWindow.onPopViewListener;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.wlstock.funi.R;
import com.wlstock.funi.adapter.OpBSAdapter;
import com.wlstock.funi.adapter.OpBSAdapter.onOpItemClick;
import com.wlstock.funi.app.FundApplication;
import com.wlstock.funi.constant.ServiceConstants;
import com.wlstock.funi.constant.URLConstant;
import com.wlstock.funi.dao.SelfFundDao;
import com.wlstock.funi.model.OpBSModel;
import com.wlstock.funi.model.OperateModel;
import com.wlstock.funi.model.SelfFundModel;
import com.wlstock.funi.request.CustomStringRequest;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.service.LatestPriceService;
import com.wlstock.funi.service.MissionService;
import com.wlstock.funi.service.QueryHisService;
import com.wlstock.funi.utils.ServiceUtil;
import com.wlstock.funi.utils.StockUtils;
import com.wlstock.funi.utils.TimeUtils;
import com.wlstock.funi.utils.ToastUtils;
import com.wlstock.funi.widget.TradeSelector;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class OpBSMainActivity extends FundBaseActivity implements OnClickListener, OnBackListener, OnMoreListener, NetWorkListener, onPopViewListener, OnTitleClickListener, onOpItemClick {
	private final String TRADE_TRACK = "2";//交易跟踪
	private final String OPERAT_LIST = "1";//操作列表
	public Activity activity;
	private Button btn_stop;
	private Button btn_start;
	private ListView listview_trade;
	private OpBSAdapter bsAdapter;
	private ArrayList<OperateModel> operateModels;
	private ArrayList<OpBSModel>  opBSModels;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_main);
		initView();
		
	}
	
	@Override
	protected void initView() {
		// TODO Auto-generated method stub
//		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.initView();
		setTitle(getString(R.string.title_traker_list));
		onBackClick(this);
		showMoreBtn(this);
		onTitleClick(this);
		
//		View public_actionbar_more = findViewById(R.id.public_actionbar_more);
//		public_actionbar_more.setVisibility(View.VISIBLE);
//		public_actionbar_more.setOnClickListener(this);
		
		btn_stop = (Button) findViewById(R.id.btn_stop);
		btn_start = (Button) findViewById(R.id.btn_start);
		findViewById(R.id.btn_query_his).setOnClickListener(this);
		findViewById(R.id.btn_to_log).setOnClickListener(this);
		listview_trade = (ListView) findViewById(R.id.listview_trade);
		btn_start.setOnClickListener(this);
		btn_stop.setOnClickListener(this);
		
		findViewById(R.id.btn_to_buy).setOnClickListener(this);
		findViewById(R.id.btn_to_set).setOnClickListener(this);
		
		operateModels = new ArrayList<OperateModel>();
		opBSModels    = new ArrayList<OpBSModel>();
		
		bsAdapter  = new OpBSAdapter(this);
		bsAdapter.setModels(opBSModels);
		bsAdapter.opBtnClick = this;
		listview_trade.setAdapter(bsAdapter);
		
		initData();
	}
	
	private void initData() {
		// TODO 初始化数据
		List<SelfFundModel> zbSelfFundModels = StockUtils.getZBSelfFundModels();
		for (int i = 0; i < zbSelfFundModels.size(); i++) {
			SelfFundDao.getInstance(this).addOrUpdateSelfModel(zbSelfFundModels.get(i));
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		
		HashMap<String, String> parms = new HashMap<String, String>();
		parms.put("act", OPERAT_LIST);
		
		CustomStringRequest curRequest = new CustomStringRequest();
		curRequest.networkResponseListener = this;
		curRequest.requestGet(URLConstant.WLHOST, URLConstant.WL_TRADE_TRACK, null, parms);
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
//		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_start:
			ServiceUtil.invokeTrackService(this);
			ServiceUtil.invokeService(this, LatestPriceService.class, ServiceConstants.LatestPriceService_ACTION_START,ServiceConstants.ELAPSED_TIME_UPDATE_PPICE);
//			ServiceUtil.invokeService(this, MissionService.class, ServiceConstants.MissionService_ACTION_START,ServiceConstants.ELAPSED_TIME_MISSION_MDAVG);
			break;
		case R.id.btn_stop:
			ServiceUtil.cancelTrackService(this);
			ServiceUtil.cancelService(this, LatestPriceService.class, ServiceConstants.LatestPriceService_ACTION_START);
			ServiceUtil.cancelService(this, MissionService.class, ServiceConstants.MissionService_ACTION_START);
			FundApplication.requestTimes = 0;
			FundApplication application =(FundApplication)getApplicationContext();
			application.getRequestQueue().stop();
			break;
		default:
			break;
		}
	}

	private List<Map<String, Object>> getMenuList()
	{
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_log));
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_set));
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_position_manager));
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_ownstock));
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_his));
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_selfmodeact));
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_selfmodeact_cordova));
		list.add(map);
		
		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_test));
		list.add(map);

		map = new HashMap<String, Object>();
		map.put("name", getResources().getString(R.string.pop_title_strategy_funds));
		list.add(map);

		return list;
	}
	
	@Override
	public void onMoreClick(View v) {
		// TODO Auto-generated method stub
		showPopUpView(getMenuList(), this);
	}

	@Override
	public void onBackClick(View v) {
		// TODO Auto-generated method stub
		this.finish();
	}
	
	@Override
	public void onTitleClick(View v) {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onErrorResponse(VolleyError error, String eventCode) {
		// TODO Auto-generated method stub
		if (eventCode.equals(URLConstant.WL_TRADE_TRACK)) {
			
		}
	}

	@Override
	public void onResponse(String response, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onResponse(String response, String eventCode) {
		// TODO 处理返回内容
			if (URLConstant.WL_TRADE_TRACK.equals(eventCode)) {
				try {
				opBSModels.clear();
				JSONObject obj = new JSONObject(response);
				Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
				String format = TimeUtils.patternDate(obj.getString("datas"));
				ArrayList<OperateModel> opModels = gson.fromJson(format, new TypeToken< List<OperateModel> >(){}.getType());

				for (int i = 0; i < opModels.size();) {
					OpBSModel    tmpBSMode = new OpBSModel();
					OperateModel tmpMode = opModels.get(i);
					
					tmpBSMode.setOpMode(tmpMode, tmpMode.getTradeType());
					int dis = 1;
					for(int j = i+1 ; j < opModels.size(); j++){
						OperateModel comMode = opModels.get(j);
						if (tmpMode.equals(comMode)) {
							//这两个是同一个人
							tmpBSMode.setOpMode(comMode, comMode.getTradeType());
							dis++;
							break;
						}
					}
					opBSModels.add(tmpBSMode);
					i = i+dis;
				}
				bsAdapter.notifyDataSetChanged();
				

				
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onViewSelectListener(String str) {
		if (str != null) {
			if (str.equals(getResources().getString(R.string.pop_title_log))) {
				//登录页面
				Intent logIt = new Intent(OpBSMainActivity.this, LoginActvity.class);
				startActivity(logIt);
			}else if (str.equals(getResources().getString(R.string.pop_title_set))) {
				//去到设置页面
				Intent setIt = new Intent(OpBSMainActivity.this, SettingActivity.class);
				startActivity(setIt);
			}else if (str.equals(getResources().getString(R.string.pop_title_his))) {
				//获取操盘手历史
				Intent i = new Intent(OpBSMainActivity.this, QueryHisService.class);
				i.setAction(ServiceConstants.QueryHisService_ACTION_START);
				startService(i);
			}else if (str.equals(getResources().getString(R.string.pop_title_test))) {
				Intent i = new Intent(OpBSMainActivity.this, TestActivity.class);
				startActivity(i);
			}else if(str.equals(getResources().getString(R.string.pop_title_selfmodeact))){
				//去到自选界面
				Intent selfFundIntent = new Intent(OpBSMainActivity.this, SelfFundActivity.class);
				startActivity(selfFundIntent);
			}else if(str.equals(getString(R.string.pop_title_selfmodeact_cordova))){
				Intent selfFundIntent = new Intent(OpBSMainActivity.this, SelfFundCordovaActivity.class);
				startActivity(selfFundIntent);
			}else if (str.equals(getResources().getString(R.string.pop_title_position_manager))) {
//				Intent intent = new Intent(OpBSMainActivity.this, PositionManagerActivity.class);
//				startActivity(intent);
			}else if (str.equals(getResources().getString(R.string.pop_title_ownstock))) {
				//我的持仓页面
				Intent intent = new Intent(OpBSMainActivity.this, MyAccountStockActivity.class);
				startActivity(intent);
			}else if (str.equals(getResources().getString(R.string.pop_title_strategy_funds))){
				Intent i = new Intent(OpBSMainActivity.this, ScrollTableActivity.class);
				startActivity(i);
			}
		}
	}

	@Override
	public void click(View v, final OperateModel model) {
		if (!FundApplication.isLogSuccess) {
			ToastUtils.showMiddleMsg(this, "请先登录");
			return;
		}
		
		TradeSelector sel = new TradeSelector(this, model.getStockName(), model.getStockNo());
		sel.show(model.getTradeType());
		
//		if (model.getTradeType() == OperateModel.TradeType_BUY) {
//			QuickBuy buy = new QuickBuy(model.getStockNo(), model.getStockName(), 5000);
//			buy.reqBuyDialog(this);
//		}else if (model.getTradeType() == OperateModel.TradeType_SELL) {
//			final MyAccountStocks account = MyAccountStockDao.getInstance(this).queryStock(model.getStockNo());
//			if (account != null && account.getStkQty() != 0) {
//				QuickSaile saile = new QuickSaile(model.getStockNo(), model.getStockName(), String.valueOf(account.getStkQty()));
//				saile.saileDialog(this);
//			} else {
//				ToastUtils.showMiddleMsg(this, "你没有持有!");		
//			}
//		}
	}
}
